#include "widget.h"
#include "ui_widget.h"
#include "mylog.h"

#include <QScreen>
#include <QGuiApplication>
#include <QDebug>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 不显示标题栏，亦无边框
    setWindowFlags(Qt::Window | Qt::FramelessWindowHint);

    // 安装自定义消息处理器（接管所有日志输出）
    //qInstallMessageHandler(MyLog::messageHandler);

    // 添加背景图片
    m_bgLabel = new QLabel(this);
    m_bgLabel->setPixmap(QPixmap("://imgs/main_ui/bk.png"));
    m_bgLabel->setScaledContents(true);
    m_bgLabel->lower();
    m_bgLabel->setGeometry(0, 0, width(), height());

    //添加顶部控件到界面
    m_mainLayout = new QVBoxLayout(this);
    m_myTopLabel = new MyTopLabel(this);
    m_mainLayout->addWidget(m_myTopLabel);
    m_mainLayout->addStretch();
    setLayout(m_mainLayout);

    connect(m_myTopLabel, &MyTopLabel::sigToClose, [=]{
        this->close();
    });
    connect(m_myTopLabel, &MyTopLabel::sigShowMin, [=]{
        this->showMinimized();
    });

    //创建界面上的输入控件
    createControl();

    // 在QTextEdit末尾添加日志，并自动滚动到底部
    connect(MyLog::getInstance(), &MyLog::logMessage, this, [=](const QString &log) {
        m_logShow->append(log);
        m_logShow->moveCursor(QTextCursor::End);
    });

    //创建存储数据对象并开启线程
    m_saveObj = new MainControl;
    m_saveObj->initThread();
    m_saveObj->startThread();

    //显示存储路径
    m_fileSavePathLine->setText(m_saveObj->getAllFileSavePath().join(" "));

    //点击应用按钮进行应用且保存,弹出ok框
    connect(m_enterPathButton, &QPushButton::clicked, [=]{
        //m_saveObj->changedSavePath(m_fileSavePathLine->text());
        // 弹出OK提示框
        QMessageBox::critical(
            this,                  // 父窗口
            "仅测试使用！",             // 标题
            "禁止使用，请更改ini文件！",      // 提示内容
            QMessageBox::Ok       // 按钮类型（仅OK按钮）
        );
    });

    //图像显示测试
    connect(m_saveObj, &MainControl::sigToShowImg, this, &Widget::onShowImg);

    //创建和上位机通讯部分
    m_hostMachineStruct = m_cfg.loadHostMachine();
    m_hostObject = new HostComputerMsg(m_hostMachineStruct.listenIP, m_hostMachineStruct.listport,
                                       m_hostMachineStruct.destIP, m_hostMachineStruct.destPort);

    connect(m_hostObject, &HostComputerMsg::sigStartStoring, m_saveObj, &MainControl::onStartStoring);
    connect(m_hostObject, &HostComputerMsg::sigStopStoring, m_saveObj, &MainControl::onStopStoring);
    connect(m_hostObject, &HostComputerMsg::sigQueryStatus, m_saveObj, &MainControl::onQueryStatus);
    connect(m_hostObject, &HostComputerMsg::sigQueryVideo, m_saveObj, &MainControl::onQueryVideo);
    connect(m_hostObject, &HostComputerMsg::sigDeleteVideo, m_saveObj, &MainControl::onDeleteVideo);
    connect(m_hostObject, &HostComputerMsg::sigTiming, m_saveObj, &MainControl::onTiming);
    connect(m_hostObject, &HostComputerMsg::sigTochangeH264Time, m_saveObj, &MainControl::onChangeH264Time);

    connect(m_saveObj, &MainControl::sigStartStoringResp, m_hostObject, &HostComputerMsg::onStartStoringResp);
    connect(m_saveObj, &MainControl::sigStopStoringResp, m_hostObject, &HostComputerMsg::onStopStoringResp);
    connect(m_saveObj, &MainControl::sigQueryStatusResp, m_hostObject, &HostComputerMsg::onQueryStatusResp);
    connect(m_saveObj, &MainControl::sigTimingResp, m_hostObject, &HostComputerMsg::onTimingResp);
    connect(m_saveObj, &MainControl::sigQueryVideoResp, m_hostObject, &HostComputerMsg::onQueryVideoNameResp);
    connect(m_saveObj, &MainControl::sigDeleteVideoResp, m_hostObject, &HostComputerMsg::onDeleteVideoResp);
    connect(m_saveObj, &MainControl::sigAllDiskFull, m_hostObject, &HostComputerMsg::onAllDiskFull);

}

// 重写resizeEvent，确保背景标签随窗口大小变化
void Widget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    if (m_bgLabel) {
        m_bgLabel->setGeometry(0, 0, width(), height());
    }
}

void Widget::createControl()
{
    // 设置天蓝色风格的样式表
    QString skyBlueStyle = R"(
       /* 通用按钮样式 */
       QPushButton {
           color: white;
           font-size: 32px;
           font-weight: bold;
           background-color: rgba(70, 180, 230, 220);  /* 天蓝色背景 */
           border-radius: 8px;
           border: 2px solid rgba(255, 255, 255, 0.7);  /* 半透明白色边框 */
           padding: 8px 16px;
           min-height: 40px;
           min-width: 100px;
       }

       /* 按钮悬停效果 */
       QPushButton:hover {
           background-color: rgba(90, 200, 250, 230);  /* 悬停时颜色变亮 */
           border-color: rgba(255, 255, 255, 0.9);  /* 边框透明度降低 */
       }

       /* 按钮点击效果 */
       QPushButton:pressed {
           background-color: rgba(50, 160, 210, 240);  /* 按下时颜色变暗 */
       }

       /* 输入框样式 */
       QLineEdit {
           color: #333;
           font-size: 32px;
           background-color: rgba(240, 248, 255, 220);  /* 淡天蓝色背景 */
           border-radius: 8px;
           border: 2px solid rgba(70, 180, 230, 0.7);  /* 天蓝色边框 */
           padding: 8px 12px;
           min-height: 40px;
       }

       /* 输入框聚焦效果 */
       QLineEdit:focus {
           border-color: rgba(70, 180, 230, 1.0);  /* 聚焦时边框颜色加深 */
           background-color: rgba(245, 252, 255, 240);  /* 背景变亮 */
       }

       /* 文本编辑框样式 */
       QTextEdit {
           color: #333;
           font-size: 32px;
           background-color: rgba(240, 248, 255, 220);  /* 淡天蓝色背景 */
           border-radius: 8px;
           border: 2px solid rgba(70, 180, 230, 0.7);  /* 天蓝色边框 */
           padding: 8px 12px;
           min-height: 120px;  /* 比 QLineEdit 更高 */
       }

       /* 文本编辑框聚焦效果 */
       QTextEdit:focus {
           border-color: rgba(70, 180, 230, 1.0);  /* 聚焦时边框颜色加深 */
           background-color: rgba(245, 252, 255, 240);  /* 背景变亮 */
       }

       /* 文本编辑框滚动条样式 */
       QTextEdit QScrollBar:vertical {
           background: rgba(230, 240, 250, 180);  /* 淡天蓝色背景 */
           width: 14px;
           margin: 16px 0 16px 0;
           border-radius: 7px;
       }

       QTextEdit QScrollBar::handle:vertical {
           background: rgba(70, 180, 230, 180);  /* 天蓝色滑块 */
           min-height: 1000px;
           border-radius: 7px;
       }

       QTextEdit QScrollBar::add-line:vertical,
       QTextEdit QScrollBar::sub-line:vertical {
           background: none;
           height: 16px;
           subcontrol-position: top;
           subcontrol-origin: margin;
       }

       QTextEdit QScrollBar::add-line:vertical {
           subcontrol-position: bottom;
       }
       /* 图像显示标签样式 */
       QLabel {
           background-color: black;  /* 黑色背景，适合图像显示 */
           border: none;  /* 无边框，避免影响图像显示 */
           padding: 0px;  /* 无内边距 */
       }
    )";

    m_choiceFileButton = new QPushButton("选择视频流存储目录", this);
    m_fileSavePathLine = new QLineEdit(this);
    m_enterPathButton = new QPushButton("应用", this);
    m_logShow = new QTextEdit(this);
    m_ShowImgLabel = new QLabel(this);

    // 应用样式表到所有控件
    m_choiceFileButton->setStyleSheet(skyBlueStyle);
    m_fileSavePathLine->setStyleSheet(skyBlueStyle);
    m_enterPathButton->setStyleSheet(skyBlueStyle);
    m_logShow->setStyleSheet(skyBlueStyle);
    m_ShowImgLabel->setStyleSheet(skyBlueStyle);
    m_fileSavePathLine->setReadOnly(true);
    m_logShow->setReadOnly(true);

    //打开文件对话框，获取目标存储路径
    connect(m_choiceFileButton, &QPushButton::clicked, [=]{
        QMessageBox::critical(
            this,
            "仅测试使用！",
            "禁止使用，请更改ini文件！",
            QMessageBox::Ok
        );
//        QString path = QFileDialog::getExistingDirectory(
//            this,
//            tr("选择目录"),
//            QDir::homePath(),
//            QFileDialog::ShowDirsOnly);

//        if(!path.isEmpty()) {
//            m_fileSavePathLine->setText(path);
//        }
    });

    //添加到布局
    m_hLayout = new QHBoxLayout(this);
    m_hLayout->addWidget(m_choiceFileButton);
    m_hLayout->addWidget(m_fileSavePathLine);
    m_hLayout->addWidget(m_enterPathButton);

    m_choiceFileButton->setFixedSize(500, 100);
    m_fileSavePathLine->setFixedSize(500, 100);
    m_enterPathButton->setFixedSize(500, 100);
    m_logShow->setFixedSize(1000, 1000);
    m_ShowImgLabel->setFixedSize(1280, 1024);

    QHBoxLayout *hLayout = new QHBoxLayout(this);
    hLayout->addWidget(m_ShowImgLabel);
    hLayout->addStretch();
    hLayout->addWidget(m_logShow);

    m_mainLayout->addLayout(m_hLayout);
    m_mainLayout->addStretch();
    //m_mainLayout->addWidget(m_logShow, 0, Qt::AlignHCenter);
    m_mainLayout->addLayout(hLayout);
    m_mainLayout->addStretch();
}

Widget::~Widget()
{
    delete ui;
    //m_cfg.saveHostMachine(m_hostMachineStruct);
    if(m_saveObj) {
        delete m_saveObj;
    }

    if(m_hostObject) {
        delete m_hostObject;
    }
}

void Widget::onShowImg(const QString ip, const quint16 port, const QByteArray arr)
{
    qDebug() << "img.size" << arr.size();
    QImage image = convert16BitGrayToQImage(arr, 320, 256);
   if (!image.isNull()) {
       // 将QImage显示在QLabel上，保持比例
       m_ShowImgLabel->setPixmap(QPixmap::fromImage(image).scaled(
           m_ShowImgLabel->size(),
           Qt::KeepAspectRatio,
           Qt::SmoothTransformation
       ));
   } else {
       m_ShowImgLabel->setText("无法显示图像");
   }
}

// 转换16bit灰度数据到QImage
QImage Widget::convert16BitGrayToQImage(const QByteArray &data, int width, int height)
{
    // 检查数据长度是否匹配
    //qDebug() << "data.size" << data.size();
    if (data.size() != width * height * 2) {
        qWarning() << "数据长度不匹配，无法转换图像";
        return QImage();
    }

    // 创建8位灰度图像（QImage不直接支持16位灰度显示）
    QImage image(width, height, QImage::Format_Grayscale8);

    // 转换16bit到8bit（根据实际情况调整映射范围）
    const quint16 *src = reinterpret_cast<const quint16*>(data.constData());
    uchar *dest = image.bits();
    int bytesPerLine = image.bytesPerLine();

    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            // 取16位数据的高8位，或进行适当缩放
            // 这里简单地右移8位，实际应用中可能需要根据数据范围调整
            quint16 value = src[y * width + x];
            dest[y * bytesPerLine + x] = static_cast<uchar>(value >> 8);

            // 或者使用完整范围映射（0-65535到0-255）
            //dest[y * bytesPerLine + x] = static_cast<uchar>(value / 256);
        }
    }

    return image;
}
